<?php
/**
 * Created by jack.
 * User: liangbo
 * Date: 2017/9/23
 * Time: 下午3:57
 * warning:此代码属于内部版权，未经许可，不得转让
 */

namespace backend\services;

use backend\models\AdminUser;
use yii;
use common\utils\CommonFun;

class UserService
{

    protected $User;

    //依赖注入
    function __construct()
    {
        $this->User = new AdminUser();
    }

    //玩家注册的逻辑
    public function UserAdd($mail, $password, $repassword)
    {
        $res = array();
        //验证邮箱
        if (isEmail($mail)) {
            //password判断
            if ($password === $repassword && isPassword($password)) {
                if ($this->ExitUser($mail))
                    $res = array("code" => -1, "messages" => "该用户已经存在", "url" => '');
                else {
                    //用户入库
                    $this->User->password = Yii::$app->security->generatePasswordHash(trim($password));
                    $this->User->uname = $mail;
                    $this->User->create_user = "admin";
                    $this->User->update_user = "admin";
                    $this->User->create_date = date("Y-m-d H:i:s");
                    $this->User->update_date = date("Y-m-d H:i:s");
                    $this->User->last_ip = @getenv('REMOTE_ADDR');
                    $this->User->email_pass = 0;
                    if ($this->User->validate() && $this->User->save()) {
                        $res = array("code" => 1, "messages" => "注册成功", "url" => '/site/index');
                        AdminUserRoleService::getInstance()->role_add($this->User->getPrimaryKey());
                        if(AdminUser::login($mail, $password, "y") == true) {
                            AdminUser::updateAll(
                                ['last_ip' => CommonFun::getClientIp()],
                                ['uname' => $mail]
                            );
                        }
                    } else
                        $res = array("code" => -1, "messages" => "注册失败", "url" => '');
                }
            } else {
                $res = array("code" => -1, "messages" => "两次密码不一致/密码不符合要求", "url" => '');
            }
        } else {
            $res = array("code" => -1, "messages" => "邮箱格式不正确", "url" => '');
        }
        return $res;
    }

    //判断用户是否存在
    public function ExitUser($mail)
    {
        $User = $this->User;
        return $User::find()->where(array("uname" => $mail))->count();
    }
    //改变邮箱验证信息
    public function MailPass($mail)
    {
        $User = $this->User;
        $model=$User::find()->where(array("uname" => $mail))->one();
        if($model)
        {
           $model->email_pass=1;
           $res=$model->save();
           return $res;

        }else{

            return 0;
        }

    }
}